package com.alex.springdata.repository;

import com.alex.springdata.entity.Person;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;

import java.util.Date;
import java.util.List;

//@RepositoryDefinition(domainClass = Person.class, idClass = Integer.class)
public interface PersonRepository extends Repository<Person, Integer> {

    Person getById(Integer id);

    Person getByLastName(String lastName);

    // where lastName LIKE ?% AND id < ?
    List<Person> getByLastNameStartingWithAndIdLessThan(String lastName, Integer id);
    List<Person> getByLastNameEndingWithAndIdLessThan(String lastName, Integer id);
    List<Person> getByLastNameContainingAndIdLessThan(String lastName, Integer id);

    // where email in (?, ?, ?) or birth ?
    List<Person> getByEmailInOrBirthLessThan(List<String> emails, Date birth);

    // 级联查询
    List<Person> getByAddress_IdGreaterThan(Integer id);

    // Query 查询语句
    @Query("select p from Person p where p.id=(select max(p2.id) from Person p2)")
    Person getMaxIdPerson();

    @Query("select p from Person p where p.lastName = ?1 and p.email = ?2")
    List<Person> getAllByQuery01(String lastName, String email);

    @Query("select p from Person p where p.lastName = :lastName and p.email = :email")
    List<Person> getAllByQuery02(@Param("email") String email, @Param("lastName") String lastName);

    @Query("select p from Person p where p.lastName like :lastName or p.email like :email")
    List<Person> getAllByQuery03(@Param("email") String email, @Param("lastName") String lastName);

    @Query("select p from Person p where p.lastName like %:lastName% and p.email like %:email%")
    List<Person> getAllByQuery04(@Param("email") String email, @Param("lastName") String lastName);

    // nativeQuery
    @Query(nativeQuery = true, value = "select count(id) from person")
    long nativeQuery01();

    @Query("update Person p set p.email = :email where p.id = :id")
    @Modifying
    void updatePersonEmail(@Param("id") Integer id, @Param("email") String email);
}
